

import UIKit


/// 可重用 Cell Id
private let EmoticonViewCellId = "EmoticonViewCellId"

class EmoticonView: UIView {

    //选中表情回调
    private var selectedEmoticonCallBack: (emoticon: Emoticon)->()
    
    //MARK: - 监听方法
    @objc private func clickItem(item: UIBarButtonItem) {
    
        print("选中分类\(item.tag)")
    
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        
        //滚动collectionView
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
        
    }
    
    
    //MARK: - 构造函数
    init(selectedEmoticon: (emoticon: Emoticon)->()) {
        // 记录闭包属性
        selectedEmoticonCallBack = selectedEmoticon
        
        // 调用父类的构造函数
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 226
        
        super.init(frame: rect)
        
        backgroundColor = UIColor.whiteColor()
        
        setUpUI()
        
        // 滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    // MARK- 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    
    private lazy var toolbar = UIToolbar()
    
    //表情包数组
    private lazy var packages = EmoticonManager.sharedManager.packages
    
// MARK: - 自定义布局
    private class EmoticonLayout: UICollectionViewFlowLayout {
    
        //自定义布局 调用
        private override func prepareLayout() {
            
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            
            //设置cell的大小
            let w = (collectionView?.bounds.width)! / col
            
            let margin = ((collectionView?.bounds.height)! - row * w) * 0.499
            
            itemSize = CGSizeMake(w, w)
            
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
    
    
    }
    
    
}

//MARK: - 设置界面
private extension EmoticonView {

    //设置界面
    private func setUpUI(){
    
        // 添加控件
        addSubview(toolbar)
    
        addSubview(collectionView)
        
        
        //设置自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(44)
            
        }
    
        
        collectionView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        
        }
        
        //准备控件
        prepareToolbar()
        prepareCollectionView()
        
    }

    
    //准备工具栏
    private func prepareToolbar() {
    
        //设置颜色
        toolbar.tintColor = UIColor.grayColor()
        
        //设置按钮内容
        var items = [UIBarButtonItem]()
        
        //设置按钮标题
        var index = 0
        
        for p in packages {
        
            items.append(UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "clickItem:"))
        
            //设置tag值
            items.last?.tag = index++
            
            //增加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        
        //移除最后一个弹簧
            items.removeLast()
        
        //设置items
        toolbar.items = items
    }
    
    
    private func prepareCollectionView() {
    
        //设置collectionView的背景颜色
        collectionView.backgroundColor = UIColor.yellowColor()
        
        //注册cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
    
        //设置数据源
        collectionView.dataSource = self
        
        //设置代理
        collectionView.delegate = self
        
    }
}

/// MARK: - 实现数据源方法
extension EmoticonView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        // 获取表情模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        
        // 执行`回调`
        selectedEmoticonCallBack(emoticon: em)
    }
    
    //一共有几组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return packages.count
        
    }

    //每组有多少数组
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return packages[section].emoticons.count
        
    }

    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        //实现cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmoticonViewCell
        
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        
        //设置cell的内容
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        //返回cell
        return cell
    }


}

/// 自定义cell
private class EmoticonViewCell: UICollectionViewCell {

    //设置表情模型
    /// emoji 的字符串编码
    var emoticon: Emoticon? {
    
        didSet{
        
            //设置按钮照片
            emoticonButton.setImage(UIImage(contentsOfFile: (emoticon?.imagePath)!), forState: UIControlState.Normal)
            
            //设置code 编码
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            //设置删除按钮
            if emoticon!.isRemoved {
            
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            
            }
        }
    
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //添加按钮
        contentView.addSubview(emoticonButton)
        
        emoticonButton.backgroundColor = UIColor.whiteColor()
        
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        //设置字体跟高度相近
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticonButton.userInteractionEnabled = false
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    //懒加载控件
    private lazy var emoticonButton: UIButton = UIButton()

}


